package com.example.cs4.mapper;

import com.example.cs4.model.ChatHistory;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Param;

import java.util.List;

@Mapper
public interface ChatHistoryMapper {

    // 获取所有公共历史消息
    @Select("SELECT * FROM chat_history WHERE receiver = 'all'")
    List<ChatHistory> selectAll();

    // 获取与指定用户相关的消息历史（包括公共消息和私聊消息）
    @Select("SELECT * FROM chat_history WHERE receiver = #{username} OR sender = #{username}")
    List<ChatHistory> selectByUser(@Param("username") String username);

    // 插入聊天历史记录
    void insert(ChatHistory chatHistory);

    // 添加 findByReceiverOrSender 方法
    @Select("SELECT * FROM chat_history WHERE receiver = #{receiver} OR sender = #{sender}")
    List<ChatHistory> findByReceiverOrSender(@Param("receiver") String receiver, @Param("sender") String sender);

    // 新增方法：根据消息ID列表标记消息为已读
    @Update("<script>" +
            "UPDATE chat_history SET isRead = true WHERE id IN " +
            "<foreach item='id' index='index' collection='messageIds' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    void markMessagesAsReadByIds(@Param("messageIds") List<Integer> messageIds);

    // 新增方法：获取未读消息数量
    @Select("SELECT COUNT(*) FROM chat_history WHERE receiver = #{username} AND isRead = false")
    int countUnreadMessages(@Param("username") String username);
}